
import { isURL } from '@/utils';
import { localhost } from '@/api/host';
import { TOKEN } from '@/config/config';

export function post (url, data, opt) {
  return request(url, data, 'POST', 'application/x-www-form-urlencoded;charset=UTF-8', opt);
}

export function postJSON (url, data, opt) {
  return request(url, data, 'POST', 'application/json', opt);
}

export function get (url, data, opt) {
  return request(url, data, 'GET', '', opt);
}

/**
 * 处理接口url
 * 小程序中，不需要跨域处理，但需要带上完整域名
 * 在 @/api 新建 host.js, 并手动配置你自己的项目运行地址, 参考 _host.js
 *
*/
export function apiURL ({ baseURL, url }) {
  const preixURL = baseURL || process.env.VUE_APP_SERVER_URL;
  let URL = '';
  // #ifdef MP
  URL = isURL(url) ? url : (localhost + preixURL) + url;
  // #endif
  // #ifdef H5
  URL = isURL(url) ? url : (preixURL) + url;
  // #endif

  console.log(URL);

  return URL;
}

/**
 *  url 接口地址，如果待http的完整域名，会忽略baseURL
 *  data 入参
 *  type 请求类型 POST GET PUT DELETE 等
 *  opt: {
      alwaysSuccess<boolean> 直接返回结果，不做code判断
      baseURL 传入覆盖默认域名前缀，默认为 process.env.VUE_APP_SERVER_UR
    }
 *
 */
export function request (url, data, type = 'POST', contentType, opt) {
  const { alwaysSuccess, baseURL, timeout = 60 * 1000 } = opt || {};

  return new Promise((resolve, reject) => {
    uni.showLoading({
      content: '请稍后...'
    });
    uni.request({
      url: apiURL({ baseURL, url }),
      method: type,
      data,
      header: {
        'Content-Type': contentType,
        'X-Access-Token': uni.getStorageSync(TOKEN) || ''
      },
      timeout,
      dataType: 'json',
      success: function (res) {
        if (alwaysSuccess) {
          resolve(res.data);
          return;
        }
        const r = res.data;
        if (r.status === true || r.code === 200 || r.success) {
          resolve({ ...r, success: true });
        } else if (r.code === 401) {
          uni.clearStorage({
            success: (res) => {
              console.log(res);
            }
          });
          uni.navigateTo({ url: '/pages/login/login' });
        } else {
          uni.showModal({
            title: '出错了',
            content: r.msg || r.message
          });
          resolve({ ...r, success: false });
          // throw new Error(r.msg || r.message)
        }
      },
      fail: function (res) {
        console.log(res);
        const result = res.data;
        reject(res);
        uni.showModal({
          title: '出错了',
          content: res.errMsg || result.msg || result.message
        });
      },
      complete: function (res) {
        uni.hideLoading();
      }
    });
  });
}
